package com.hmdp.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 查询商店类型列表
     * @return
     */
    @Override
    public Result qureryTypeList() {
        //查询redis是否有对应数据
        String shopTypeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        //如果有则返回
        if(shopTypeJson != null){
            JSONArray jsonArray = JSONUtil.parseArray(shopTypeJson);
            List<ShopType> shopTypes = jsonArray.toList(ShopType.class);
            return Result.ok(shopTypes);
        }
        //如果没有就去数据库里查询数据
        List<ShopType> shopTypeListlist = query().list();
        //如果没有就返回错误信息
        if(shopTypeListlist==null || shopTypeListlist.isEmpty()){
            return Result.fail("找不到店铺类型！");
        }
        //如果有就转换为json字符串并且写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY,JSONUtil.toJsonStr(shopTypeListlist),CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        //返回结果
        return Result.ok(shopTypeListlist);
    }
}
